# ！/usr/bin/python
# coding:utf-8

import json
import paramiko
from io import StringIO


def sftp_client(host,port,key_str,user,password,src_file,dest_file):
    if key_str:
        private_key = paramiko.RSAKey(file_obj=StringIO(key_str))
    else:
        private_key = None
    transport = paramiko.Transport((host, port))
    transport.connect(username=user, password=password,pkey=private_key)
    sftp = paramiko.SFTPClient.from_transport(transport)
    sftp.put(src_file,dest_file)
    sftp.close()
    return True


def ssh_exec(host,port,key_str,user,password,cmd):
    if key_str:
        private_key = paramiko.RSAKey(file_obj=StringIO(key_str))
    else:
        private_key = None
    # 创建ssh对象
    ssh = paramiko.SSHClient()
    # 允许连接不在know_hosts 文件中的主机
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 连接服务器
    ssh.connect(hostname=host, port=port, username=user, password=password,pkey=private_key)

    # 执行命令
    stdin, stdout, stderr = ssh.exec_command(cmd)
    # 获取命令结果
    stdout.read()
    # 关闭连接
    ssh.close()
    return True

if __name__ == "__main__":
    host = "192.168.1.153"
    port = 22
    user = "root"
    password = "xxxxxx"
    key_str = None
    src_file = r"/tmp/pycharm_project_108/plugins/scripts/salt_install.sh"
    dest_file = "/opt/salt_install.sh"
    cmd = "ls /opt/salt_install.sh"
    sftp_client(host,port,key_str,user,password,src_file,dest_file)
    ssh_exec(host, port, key_str, user, password, cmd)
